package com.holis.order.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.holis.order.common.R;
import com.holis.order.common.RedisCache;
import com.holis.order.entity.Dto.userDto;
import com.holis.order.entity.HuoliEntity;
import com.holis.order.entity.userEntity;
import com.holis.order.service.HuoliService;
import com.holis.order.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author lxx
 * @email lixiaoxiao97@qq.com
 * @date 2020-12-04 17:00:30
 */
@RestController
public class loginController {
    @Autowired
    userService userService;
    @Autowired
    HuoliService huoliService;
    @Autowired
    RedisCache redisCache;

    /**
     * login 登录
     * @param userDto 登录数据接收，存入redis
     * @return
     */
    @RequestMapping("/login")
    public R login(@RequestBody userDto userDto){
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        Map<String,Object> data = new HashMap<>();
        if("".equals(username) || "".equals(password))
            return R.error(400,"请输入正确的用户名和密码");
        userEntity user = userService.getOne(
                new QueryWrapper<userEntity>().eq("username",username).and(i -> i.eq("password", password)));
        if(user == null){
            return R.error(400,"请输入正确的用户名和密码");
        }else {
            //成功登录
            user.getUsername().equals(username);
            List<HuoliEntity> userOrder =
                    huoliService.list(new QueryWrapper<HuoliEntity>().eq("user_id", user.getUserId()));
            String uuid =  UUID.randomUUID().toString();
            data.put("user",user);
            data.put("order",userOrder);
            data.put("uuid",uuid);
            System.out.println(uuid);
            //存入redis中
            redisCache.setCacheObject(uuid,data,30, TimeUnit.MINUTES);
        }

        return R.ok().put("data",data);
    }

    /**
     * delete: 退出登录
     * @param servletRequest
     * @return
     */
    @RequestMapping("/logout")
    public R delete(HttpServletRequest servletRequest){
        String uuid = servletRequest.getHeader("uuid");
        if (uuid == null) {
            return R.ok();
        }
        redisCache.deleteObject(uuid);
        return R.ok();
    }
}
